package ar.com.tallerdos.smartdinner.activity;

import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import ar.com.tallerdos.smartdinner.R;
import ar.com.tallerdos.smartdinner.business.ComidaBusiness;
import ar.com.tallerdos.smartdinner.model.Comida;
import ar.com.tallerdos.smartdinner.sync.MaestroSincronizador;

public class ComidasLista extends Activity {
    
    public final static String COMIDA_SELECCIONADA = "ar.com.tallerdos.smartdinner.activity.ComidasLista.COMIDA_SELECCIONADA";
    private List<Comida> comidas;
    private BaseAdapter comidasAdapter;
    private MaestroSincronizador sincronizador;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	
	this.sincronizador = MaestroSincronizador.getInstancia();
	sincronizador.start();
	
	setContentView(R.layout.comida_lista_activity);
	
	ListView comidasListView = (ListView) findViewById(R.id.comidasLista);

	comidas = ComidaBusiness.findAll();

	this.comidasAdapter = new ArrayAdapter<Comida>(this,
		android.R.layout.simple_list_item_1, comidas);
	comidasListView.setAdapter(this.comidasAdapter);
	comidasListView.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view,
		    int position, long id) {
		Intent intent = new Intent(ComidasLista.this, ComidaActivity.class);
		intent.putExtra(COMIDA_SELECCIONADA, comidas.get(position).getId().intValue());
		startActivity(intent);
	    }
	});
    }
    
    public void abrirMesa(View view) {
	Intent intent = new Intent(this, AbrirMesaActivity.class);
	startActivityForResult(intent, 1);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	if (requestCode == 1) {

	    if (resultCode == RESULT_OK) {
		int idComida = data.getIntExtra("result", 0);
		Comida comidaNueva = ComidaBusiness.findById(Integer.valueOf(idComida));
		this.comidas.add(comidaNueva);
		ComidasLista.this.comidasAdapter.notifyDataSetChanged();
	    }
	    if (resultCode == RESULT_CANCELED) {
		// Write your code if there's no result
	    }
	}
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.sincronizador = null;
        MaestroSincronizador.getInstancia().parar();
    }

}
